//
//  AnalysisViewController.m
//  PurchasingMeeting
//
//  Created by zhuang yihang on 7/12/13.
//  Copyright (c) 2013 YX. All rights reserved.
//

#import "AnalysisViewController.h"
#import "DataManager.h"
#import "KeyObject.h"
#import "FPPopoverController.h"
#import "WebServiceManager.h"
@interface AnalysisViewController (){
    NSArray *keyCategories_;
       NSMutableArray *filterBtns_;
}

@end

@implementation AnalysisViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setNavTitle:@"数据分析"];
#ifdef DHH_iOS
        UITabBarItem *tabBarItem = [[UITabBarItem alloc] initWithTitle:self.title image:[UIImage imageNamed:@"main_analysis_iphone.png"] tag:0];
        self.tabBarItem = tabBarItem;
#endif
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    KeyFilter = [[NSMutableArray alloc]init];
    
	// Do any additional setup after loading the view.
    UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
    [b setImage:[UIImage imageNamed:@"homepage.png"] forState:UIControlStateNormal];
    b.frame = CGRectMake(10, 10, [UIImage imageNamed:@"homepage.png"].size.width, [UIImage imageNamed:@"homepage.png"].size.height);
    [b addTarget:self action:@selector(ret) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithCustomView:b];
    self.navigationItem.leftBarButtonItem = left;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshnum:) name:@"refreshnum" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshshop:) name:@"refreshshop" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshReport:) name:@"refreshReport" object:nil];
    
    
    NSArray*  tmpkeyCategories = [[DataManager sharedManager] getKeyCategories];
    
    //只取前两个过滤条件
    keyCategories_ = [[NSArray alloc]initWithObjects:tmpkeyCategories[0],tmpkeyCategories[1], nil];
    countarr = [[NSMutableArray alloc]init];
    pricearr = [[NSMutableArray alloc]init];
    titlearr = [[NSMutableArray alloc]init];
    colorarr = [[NSMutableArray alloc]init];

#ifdef DHH_iOS
    UIImageView *back = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back.png"]];
    back.frame = CGRectMake(0, 0, [UIImage imageNamed:@"back.png"].size.width, [UIImage imageNamed:@"back.png"].size.height);
    [self.view addSubview:back];
    
    tint = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"detail_tint.png"]];
    tint.frame = CGRectMake(0, 0, [UIImage imageNamed:@"detail_tint.png"].size.width, [UIImage imageNamed:@"detail_tint.png"].size.height);
    tint.userInteractionEnabled = YES;
    [self.view addSubview:tint];
    
    UIButton *btn = [[UIHelper getInstance] createButtonByFrame:CGRectMake(0, 0, 100, tint.height)];
    [btn setImage:[UIImage imageNamed:@"order_next.png"] forState:UIControlStateNormal];
    [tint addSubview:btn];
    [btn setBackgroundColor:[UIColor clearColor]];
    [btn setTitle:@"品类分析" forState:UIControlStateNormal];
    
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
    // b.left = (b.width+30)*i;
    [btn addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 100;
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
    
    cloth = [[UIHelper getInstance] createButtonByFrame:CGRectMake(110, 0, 100, tint.height)];
    [cloth setImage:[UIImage imageNamed:@"order_next.png"] forState:UIControlStateNormal];
    [tint addSubview:cloth];
    [cloth setBackgroundColor:[UIColor clearColor]];
    [cloth setTitle:@"服装" forState:UIControlStateNormal];
    
    [cloth setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    cloth.titleLabel.font = [UIFont systemFontOfSize:14];
    //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
    // b.left = (b.width+30)*i;
    [cloth addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
    cloth.tag = 101;
    cloth.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
    
    totalshop = [[UIHelper getInstance] createButtonByFrame:CGRectMake(220, 0, 100, tint.height)];
    [totalshop setImage:[UIImage imageNamed:@"order_next.png"] forState:UIControlStateNormal];
    [tint addSubview:totalshop];
    [totalshop setBackgroundColor:[UIColor clearColor]];
    [totalshop setTitle:@"全部店铺" forState:UIControlStateNormal];
    
    [totalshop setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    totalshop.titleLabel.font = [UIFont systemFontOfSize:14];
    //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
    // b.left = (b.width+30)*i;
    [totalshop addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
    totalshop.tag = 102;
    totalshop.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
    
    view = [[UIView alloc]initWithFrame:CGRectMake(0, tint.height, self.view.width, self.view.height-tint.height)];
    [self.view addSubview:view];
    [self refreshiphone:0 coatkeys:nil];
#else
    UIImageView *back = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back.png"]];
    back.frame = CGRectMake(0, 0, [UIImage imageNamed:@"back.png"].size.width, [UIImage imageNamed:@"back.png"].size.height);
    [self.view addSubview:back];
    
    UIImage *tintImage = [[UIHelper getInstance] getBundleImage:@"detail_tint.png"];
    tintImage = [tintImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, 16, 0, 16)];

    tint = [[UIImageView alloc]initWithImage:tintImage];
    tint.width = 1024;
    tint.userInteractionEnabled = YES;
    [self.view addSubview:tint];
    
    UIButton *detail = [UIButton buttonWithType:UIButtonTypeCustom];
    detail.frame = CGRectMake(0, 0, 100, 30);
    detail.backgroundColor = [UIColor blackColor];
    [detail setTitle:@"报表摘要" forState:UIControlStateNormal];
    detail.center = CGPointMake(780, tint.height/2);
    [detail addTarget:self action:@selector(detail) forControlEvents:UIControlEventTouchUpInside];
    [tint addSubview:detail];
    
    UIButton *graphic = [UIButton buttonWithType:UIButtonTypeCustom];
    graphic.frame = CGRectMake(0, 0, 100, 30);
    graphic.backgroundColor = [UIColor blackColor];
    [graphic setTitle:@"图形分析" forState:UIControlStateNormal];
    graphic.center = CGPointMake(900, tint.height/2);
    [graphic addTarget:self action:@selector(graphic) forControlEvents:UIControlEventTouchUpInside];
    [tint addSubview:graphic];
    //设置报表类型筛选
    UIButton *btn = [[UIHelper getInstance] createButtonByFrame:CGRectMake(0, 0, 150, tint.height)];
    [btn setImage:[UIImage imageNamed:@"order_next.png"] forState:UIControlStateNormal];
    [tint addSubview:btn];
    [btn setBackgroundColor:[UIColor clearColor]];
    
    reporttype = [[DataManager sharedManager]getStatType];
    
    [btn setTitle:[[reporttype objectAtIndex:0] objectForKey:@"name"] forState:UIControlStateNormal];
    
    selecedReport = 0;
    
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
    // b.left = (b.width+30)*i;
    [btn addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
    btn.tag = 100;
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, 130, 0, 0);
    filterBtns_ = [NSMutableArray array];
    //设置筛选条件
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        
        UIButton *b = [[UIHelper getInstance] createButtonByFrame:CGRectMake(0, 0, 100, tint.height)];
        [b setImage:[UIImage imageNamed:@"order_next.png"] forState:UIControlStateNormal];
        [tint addSubview:b];
        [b setBackgroundColor:[UIColor clearColor]];
        [b setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        b.titleLabel.font = [UIFont systemFontOfSize:14];
        b.left = (b.width+10)*i+150;
        [b addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
        b.tag = [[keyCategories_ objectAtIndex:i] intValue]+110;
        b.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
        [filterBtns_ addObject:b];
        [b setHidden:YES];
        KeyObject* firstkey = [[[DataManager sharedManager]getKeyObjects:(i+1)]objectAtIndex:0];
        [b setTitle:firstkey.keyName forState:UIControlStateNormal];
        [KeyFilter addObject:firstkey];
        
    }
    
    
    //初始化菜单
    for ( int i = 0; i < keyCategories_.count; i++ ) {
        
        [self updateKeyButton:i+1];
    }
    
    
    /*先去掉多店铺*/
    
//    //设置店铺的筛选条件
//    totalshop = [[UIHelper getInstance] createButtonByFrame:CGRectMake(850, 0, 100, tint.height)];
//    
//    [totalshop setImage:[UIImage imageNamed:@"order_next.png"] forState:UIControlStateNormal];
//    [tint addSubview:totalshop];
//    [totalshop setBackgroundColor:[UIColor clearColor]];
//    [totalshop setTitle:@"全部店铺" forState:UIControlStateNormal];
//    
//    [totalshop setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//    totalshop.titleLabel.font = [UIFont systemFontOfSize:14];
//    //  b.backgroundColor = [[UIHelper getInstance] getRandomColor];
//    // b.left = (b.width+30)*i;
//    [totalshop addTarget:self action:@selector(keyClicked:) forControlEvents:UIControlEventTouchUpInside];
//    totalshop.tag = 102;
//    totalshop.imageEdgeInsets = UIEdgeInsetsMake(0, 90, 0, 0);
    
    view = [[UIView alloc]initWithFrame:CGRectMake(0, tint.height, self.view.width, self.view.height-tint.height)];
    [self.view addSubview:view];
    [self newrefresh:selectedShopid  ReportId:selecedReport];
#endif
}
-(void)ret
{
#ifdef DHH_iOS
    [self.navigationController.tabBarController.navigationController popViewControllerAnimated:YES];
#else
    [self.navigationController popViewControllerAnimated:YES];
#endif
}

- (void)updateKeyButton:(int)selectedCategory{
    
    KeyObject* key = [KeyFilter objectAtIndex:selectedCategory-1];
    
    UIButton* btn = (UIButton*)[filterBtns_ objectAtIndex:key.categoryCode-1];
    
    [btn setTitle:key.keyName forState:UIControlStateNormal];
    
    //层层往下找，是否有连动的子级菜单
    NSArray*child = [[DataManager sharedManager]getChildrenKeyObjects:key.keyID];
    
    if (child.count>0) {
        //取第一个值作为过滤条件
        KeyObject *firstchild = [child objectAtIndex:0];
        
        [KeyFilter replaceObjectAtIndex:firstchild.categoryCode-1 withObject:firstchild];
        
        UIButton* btn = (UIButton*)[filterBtns_ objectAtIndex:firstchild.categoryCode-1];
        
        [btn setTitle:firstchild.keyName forState:UIControlStateNormal];
        
        //如果能找到子集菜单则递归调用子集
        [self updateKeyButton:firstchild.categoryCode];
    }
    
}


/*
-(void)refreshiphone:(int)shoptag coatkeys:(NSArray *)coatkeys
{
    [view removeAllSubviews];
    totalcount = 0;
    totalcountrate = 0;
    totalprice = 0;
    totalpricerate = 0;
    totalsku = 0;
    totalskurate = 0;
    totalcate = 0;
    totalcaterate = 0;
    totalnum = 0;
    totalpricenum = 0;
    
    scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 70-tint.height, 300, 380)];
    scroll.alwaysBounceVertical = YES;
    scroll.alwaysBounceHorizontal = YES;
    scroll.showsHorizontalScrollIndicator = YES;
    scroll.bounces = NO;
    [view addSubview:scroll];
    
    
    for (int i = 0; i<9; i++) {
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100*i, 0, 99, 35)];
        label.backgroundColor = [UIColor orangeColor];
        if (i==0) {
            label.text = @"分类";
        }
        else if(i==1)
        {
            label.text = @"数量";
        }
        else if(i==2||i==4||i==6||i==8)
        {
            label.text = @"占比";
        }
        else if(i==3)
        {
            label.text = @"金额";
        }
        else if(i==5)
        {
            label.text = @"sku数";
        }
        else if(i==7)
        {
            label.text = @"款数";
        }
        
        label.textAlignment = NSTextAlignmentCenter;
        [scroll addSubview:label];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(100*(i+1)-1, 0, 1, 35)];
        line.backgroundColor = [UIColor clearColor];
        [scroll addSubview:line];
    }
    scroll.contentSize = CGSizeMake(scroll.width, 35);
    
   // keyCategories_ = [[DataManager sharedManager] getKeyCategories];
   // int tag = [[keyCategories_ objectAtIndex:1] intValue];
    NSArray *keys = coatkeys;
    NSMutableArray *items = [NSMutableArray array];
    for ( KeyObject *obj in keys ) {
        [items addObject:obj.keyName];
    }
    
    product = [[DataManager sharedManager] getOrderedProducts];
    for (int i=0; i<product.count; i++) {
        ProductObject *obj = [product objectAtIndex:i];
        totalnum += [[DataManager sharedManager]getOrderNumberWithProduct:obj];
        totalpricenum += [[DataManager sharedManager]getOrderNumberWithProduct:obj] * obj.pSale;
    }
    
    NSMutableArray *items1 = [NSMutableArray array];
    for (int i = 0; i<items.count; i++) {
        num = 0;
        product = [[DataManager sharedManager] getOrderedProducts];
        for (int k=0; k<product.count; k++) {
            ProductObject *obj = [product objectAtIndex:k];
            if ([obj.pName isEqualToString:[items objectAtIndex:i]]) {
                if (shoptag==0) {
                    num += [[DataManager sharedManager]getOrderNumberWithProduct:obj];
                }
                else
                {
                    NSArray *shop = [[DataManager sharedManager]getShopList];
                    ShopObject *shopobj = [shop objectAtIndex:shoptag-1];
                    num += [[DataManager sharedManager]getOrderNumberWithProduct:obj shopid:shopobj.shopID];
                }

            }
        }
        if (num>0) {
            [items1 addObject:[items objectAtIndex:i]];
        }
    }
    
    for (int i = 0; i<items1.count; i++) {
        num = 0;
        float pricenum = 0;
        product = [[DataManager sharedManager] getOrderedProducts];
        for (int k=0; k<product.count; k++) {
            ProductObject *obj = [product objectAtIndex:k];
            if ([obj.pName isEqualToString:[items1 objectAtIndex:i]]) {
                if (shoptag==0) {
                    num += [[DataManager sharedManager]getOrderNumberWithProduct:obj];
                    pricenum += [[DataManager sharedManager]getOrderNumberWithProduct:obj] * obj.pSale;
                }
                else
                {
                    NSArray *shop = [[DataManager sharedManager]getShopList];
                    ShopObject *shopobj = [shop objectAtIndex:shoptag-1];
                    num += [[DataManager sharedManager]getOrderNumberWithProduct:obj shopid:shopobj.shopID];
                    pricenum += [[DataManager sharedManager]getOrderNumberWithProduct:obj shopid:shopobj.shopID] * obj.pSale;
                }
            }
        }
        for (int j=0; j<9; j++) {
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100*j, 35*(i+1), 99, 35)];
            if (i%2==0) {
                label.backgroundColor = [UIColor yellowColor];
            }
            else
            {
                label.backgroundColor = [UIColor orangeColor];
            }
            if (j==0) {
                label.text = [items1 objectAtIndex:i];
            }
            else if(j==1)
            {
                NSString *str = [NSString stringWithFormat:@"%.0f",num];
                label.text = str;
                totalcount += [label.text intValue];
            }
            else if(j==2)
            {
                NSString *str = [NSString stringWithFormat:@"%.2f%%",num/totalnum * 100];
                label.text = str;
                totalcountrate += [label.text floatValue];
            }
            else if(j==3)
            {
                NSString *str = [NSString stringWithFormat:@"%.0f",pricenum];
                label.text = str;
                totalprice += [label.text intValue];
            }
            else if(j==4)
            {
                NSString *str = [NSString stringWithFormat:@"%.2f%%",pricenum/totalpricenum * 100];
                label.text = str;
                totalpricerate += [label.text floatValue];
            }
            else if(j==5)
            {
                label.text = @"2";
                totalsku += [label.text intValue];
            }
            else if(j==6)
            {
                label.text = @"50%";
                totalskurate += [label.text intValue];
            }
            else if(j==7)
            {
                label.text = @"2";
                totalcate += [label.text intValue];
            }
            else if(j==8)
            {
                label.text = @"50%";
                totalcaterate += [label.text intValue];
            }
            
            label.textAlignment = NSTextAlignmentCenter;
            [scroll addSubview:label];
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(100*(j+1)-1, 35*(i+1), 1, 35)];
            line.backgroundColor = [UIColor clearColor];
            [scroll addSubview:line];
            scroll.contentSize = CGSizeMake(100 * (j+1), 35 * (i+2));
        }
        scroll.contentSize = CGSizeMake(scroll.contentSize.width, 35 * (i+2));
    }
    for (int i = 0; i<9; i++) {
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100*i, scroll.contentSize.height, 99, 35)];
        label.backgroundColor = [UIColor orangeColor];
        if (i==0) {
            label.text = @"总计";
        }
        else if(i==1)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalcount];
            label.text = str;
        }
        else if(i==2)
        {
            NSString *str = [NSString stringWithFormat:@"%.2f%%",totalcountrate];
            label.text = str;
            
        }
        else if(i==3)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalprice];
            label.text = str;
        }
        else if(i==4)
        {
            NSString *str = [NSString stringWithFormat:@"%.2f%%",totalpricerate];
            label.text = str;
        }
        else if(i==5)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalsku];
            label.text = str;
        }
        else if(i==6)
        {
            NSString *str = [NSString stringWithFormat:@"%d%%",totalskurate];
            label.text = str;
        }
        else if(i==7)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalcate];
            label.text = str;
        }
        else if(i==8)
        {
            NSString *str = [NSString stringWithFormat:@"%d%%",totalcaterate];
            label.text = str;
        }
        
        label.textAlignment = NSTextAlignmentCenter;
        [scroll addSubview:label];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(100*(i+1)-1, scroll.contentSize.height, 1, 35)];
        line.backgroundColor = [UIColor clearColor];
        [scroll addSubview:line];
    }
    scroll.contentSize = CGSizeMake(scroll.contentSize.width, scroll.contentSize.height+35);
}
 */


-(void)refresh:(int)shoptag keyname:(KeyObject *)keyname
{
    
    [view removeAllSubviews];
    view = [[UIView alloc]initWithFrame:CGRectMake(0, tint.height, self.view.width, self.view.height-tint.height)];
    [self.view addSubview:view];
    
    totalcount = 0;
    totalcountrate = 0;
    totalprice = 0;
    totalpricerate = 0;
    totalsku = 0;
    totalskurate = 0;
    totalcate = 0;
    totalcaterate = 0;
    totalnum = 0;
    totalpricenum = 0;

    scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(20, 70-tint.height, 900, 600)];
    scroll.centerX = 512;
    scroll.alwaysBounceVertical = YES;
    scroll.alwaysBounceHorizontal = YES;
    scroll.showsHorizontalScrollIndicator = YES;
    scroll.bounces = NO;
    [view addSubview:scroll];

    
    for (int i = 0; i<9; i++) {
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100*i, 0, 99, 35)];
        label.backgroundColor = [UIColor orangeColor];
        if (i==0) {
            label.text = @"分类";
        }
        else if(i==1)
        {
            label.text = @"数量";
        }
        else if(i==2||i==4||i==6||i==8)
        {
            label.text = @"占比";
        }
        else if(i==3)
        {
            label.text = @"金额";
        }
        else if(i==5)
        {
            label.text = @"sku数";
        }
        else if(i==7)
        {
            label.text = @"款数";
        }
        
        label.textAlignment = NSTextAlignmentCenter;
        [scroll addSubview:label];
        
//        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(100*(i+1)-1, 0, 1, 35)];
//        line.backgroundColor = [UIColor clearColor];
//        [scroll addSubview:line];
    }
    scroll.contentSize = CGSizeMake(scroll.width, 35);
    
  // keyCategories_ = [[DataManager sharedManager] getKeyCategories];
  //  int tag = [[keyCategories_ objectAtIndex:1] intValue];
    /*
    NSArray *keys = coatkeys;
    NSMutableArray *items = [NSMutableArray array];
    for ( KeyObject *obj in keys ) {
        [items addObject:obj.keyName];
    }
     */
    
    product = [[DataManager sharedManager] getOrderStat:keyname Shopid:nil];
    /*
    for (int i=0; i<product.count; i++) {
        ProductObject *obj = [product objectAtIndex:i];
        totalnum += [[DataManager sharedManager]getOrderNumberWithProduct:obj];
        totalpricenum += [[DataManager sharedManager]getOrderNumberWithProduct:obj] * obj.pSale;
    }
    
    NSMutableArray *items1 = [NSMutableArray array];
    for (int i = 0; i<items.count; i++) {
        num = 0;
        product = [[DataManager sharedManager] getOrderedProducts];
        for (int k=0; k<product.count; k++) {
            ProductObject *obj = [product objectAtIndex:k];
            if ([obj.pName isEqualToString:[items objectAtIndex:i]]) {
                if (shoptag==0) {
                    num += [[DataManager sharedManager]getOrderNumberWithProduct:obj];
                }
                else
                {
                    NSArray *shop = [[DataManager sharedManager]getShopList];
                    ShopObject *shopobj = [shop objectAtIndex:shoptag-1];
                    num += [[DataManager sharedManager]getOrderNumberWithProduct:obj shopid:shopobj.shopID];
                }
            }
        }
        if (num>0) {
            [items1 addObject:[items objectAtIndex:i]];
        }
    }
    */
    for (int i = 0; i<product.count; i++) {
        NSDictionary *dic = [product objectAtIndex:i];
        for (int j=0; j<9; j++) {
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100*j, 35*(i+1), 99, 35)];
            if (i%2==0) {
                label.backgroundColor = [UIColor yellowColor];
            }
            else
            {
                label.backgroundColor = [UIColor orangeColor];
            }
            if (j==0) {
                label.text = [dic objectForKey:@"name"];
            }
            else if(j==1)
            {
                NSString *count = [dic objectForKey:@"count"];
                NSString *str = [NSString stringWithFormat:@"%@",count];
                label.text = str;
                totalcount += [label.text intValue];
            }
            else if(j==2)
            {
                NSString *str = [NSString stringWithFormat:@"%.2f%%",num/totalnum * 100];
                label.text = str;
                totalcountrate += [label.text floatValue];
            }
            else if(j==3)
            {
                NSString *amount = [dic objectForKey:@"amount"];
                NSString *str = [NSString stringWithFormat:@"%@",amount];
                label.text = str;
                totalprice += [label.text intValue];
            }
            else if(j==4)
            {
               // NSString *str = [NSString stringWithFormat:@"%.2f%%",pricenum/totalpricenum * 100];
               // label.text = str;

                totalpricerate += [label.text floatValue];
            }
            else if(j==5)
            {
                label.text = @"2";
                totalsku += [label.text intValue];
            }
            else if(j==6)
            {
                label.text = @"50%";
                totalskurate += [label.text intValue];
            }
            else if(j==7)
            {
                label.text = @"2";
                totalcate += [label.text intValue];
            }
            else if(j==8)
            {
                label.text = @"50%";
                totalcaterate += [label.text intValue];
            }
            
            label.textAlignment = NSTextAlignmentCenter;
            [scroll addSubview:label];
            
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(100*(j+1)-1, 35*(i+1), 1, 35)];
            line.backgroundColor = [UIColor clearColor];
            [scroll addSubview:line];
        }
        scroll.contentSize = CGSizeMake(scroll.width, 35 * (i+2));
    }
    for (int i = 0; i<9; i++) {
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100*i, scroll.contentSize.height, 99, 35)];
        label.backgroundColor = [UIColor orangeColor];
        if (i==0) {
            label.text = @"总计";
        }
        else if(i==1)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalcount];
            label.text = str;
        }
        else if(i==2)
        {
            NSString *str = [NSString stringWithFormat:@"%.2f%%",totalcountrate];
            label.text = str;

        }
        else if(i==3)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalprice];
            label.text = str;
        }
        else if(i==4)
        {
            NSString *str = [NSString stringWithFormat:@"%.2f%%",totalpricerate];
            label.text = str;
        }
        else if(i==5)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalsku];
            label.text = str;
        }
        else if(i==6)
        {
            NSString *str = [NSString stringWithFormat:@"%d%%",totalskurate];
            label.text = str;
        }
        else if(i==7)
        {
            NSString *str = [NSString stringWithFormat:@"%d",totalcate];
            label.text = str;
        }
        else if(i==8)
        {
            NSString *str = [NSString stringWithFormat:@"%d%%",totalcaterate];
            label.text = str;
        }
        
        label.textAlignment = NSTextAlignmentCenter;
        [scroll addSubview:label];
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(100*(i+1)-1, scroll.contentSize.height, 1, 35)];
        line.backgroundColor = [UIColor clearColor];
        [scroll addSubview:line];
    }
    scroll.contentSize = CGSizeMake(scroll.width, scroll.contentSize.height+35);
}


-(void)newrefresh:(NSString*)shopid  ReportId:(int)reportId
{
    [countarr removeAllObjects];
    [pricearr removeAllObjects];
    [titlearr removeAllObjects];
    [view removeAllSubviews];
    view = [[UIView alloc]initWithFrame:CGRectMake(0, tint.height, self.view.width, self.view.height-tint.height)];
    [self.view addSubview:view];
    
    scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(20, 70-tint.height, 900, 600)];
    scroll.centerX = 512;
    scroll.alwaysBounceVertical = YES;
    scroll.alwaysBounceHorizontal = YES;
    scroll.showsHorizontalScrollIndicator = YES;
    scroll.bounces = NO;
    [view addSubview:scroll];
    
   
    //构建报表列名称
    NSArray* columname = [[DataManager sharedManager]getOrderReportColumnCName:reportId];
    
    int cellwidth = 900/columname.count;
    
    for (int i = 0; i<columname.count; i++) {
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(cellwidth*i, 0, cellwidth-1, 35)];
        label.backgroundColor = [UIColor colorWithRed:255/255.0 green:196/255.0 blue:136/255.0 alpha:1];
        label.text = [columname objectAtIndex:i];
        if ([label.text isEqualToString:@"数量比"]) {
            countcolumn = i;
        }
        if ([label.text isEqualToString:@"金额比"]) {
            pricecolumn = i;
        }
        if ([label.text hasSuffix:@"名称"]) {
            titlecolumn = i;
        }
        label.textAlignment = NSTextAlignmentCenter;
        [scroll addSubview:label];
    }
    scroll.contentSize = CGSizeMake(scroll.width, 35);
    
    //构建报表详细数据
    if (reportId<7) {
        NSArray* arr = [[DataManager sharedManager]getOrderReport:reportId Filter:nil Shopid:shopid];
        
        for (int i = 0; i<arr.count; i++) {
            NSArray *dic = [arr objectAtIndex:i];
            for (int j=0; j<columname.count; j++) {
                UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(cellwidth*j, 35*(i+1), cellwidth-1, 35)];
                if (i%2==0) {
                    label.backgroundColor = [UIColor colorWithRed:193/255.0 green:210/255.0 blue:240/255.0 alpha:1];
                }
                else
                {
                    label.backgroundColor = [UIColor colorWithRed:255/255.0 green:196/255.0 blue:136/255.0 alpha:1];
                }
                
                label.text = [dic objectAtIndex:j];
                label.adjustsFontSizeToFitWidth = YES;
                
                label.textAlignment = NSTextAlignmentCenter;
                [scroll addSubview:label];
            }
            scroll.contentSize = CGSizeMake(scroll.width, 35 * (i+2));
            [countarr addObject:[dic objectAtIndex:countcolumn]];
            [pricearr addObject:[dic objectAtIndex:pricecolumn]];
            [titlearr addObject:[dic objectAtIndex:titlecolumn]];
        }

    }
    else {
        
        NSString* sku=@"";
        if (reportId>=9&&!shopid) {
            
            ShopObject* shopobj= [[[DataManager sharedManager]getShopList] objectAtIndex:0];
            
            shopid = shopobj.shopID;
        }
        if (reportId>9) {
            KeyObject* key = [KeyFilter objectAtIndex:1];
            
            sku = key.keyName;
        }
        
        [[WebServiceManager sharedManager ] getServerReport: [[DataManager sharedManager]getUserObject].userCode ShopID:shopid SKU:sku QueryType:[NSString stringWithFormat:@"%d", reportId+1 ]completion:^(NSArray *report){
            
            for (int i = 0; i<report.count; i++) {
                NSDictionary *dic = [report objectAtIndex:i];
                
                NSArray* arr = [[DataManager sharedManager]transReport:dic];
                if (arr.count>0) {
                    
                    
                    for (int j=0; j<columname.count; j++) {
                        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(cellwidth*j, 35*(i+1), cellwidth-1, 35)];
                        if (i%2==0) {
                            label.backgroundColor = [UIColor colorWithRed:193/255.0 green:210/255.0 blue:240/255.0 alpha:1];
                        }
                        else
                        {
                            label.backgroundColor = [UIColor colorWithRed:255/255.0 green:196/255.0 blue:136/255.0 alpha:1];
                        }
                        
                        label.text = [arr objectAtIndex:j];
                        label.adjustsFontSizeToFitWidth = YES;
                        
                        label.textAlignment = NSTextAlignmentCenter;
                        [scroll addSubview:label];
                        
                    }
                    scroll.contentSize = CGSizeMake(scroll.width, 35 * (i+2));
                   // [countarr addObject:[arr objectAtIndex:countcolumn]];
                   // [pricearr addObject:[arr objectAtIndex:pricecolumn]];
                   // [titlearr addObject:[arr objectAtIndex:titlecolumn]];
                }
            }
            
        }];
    }

}





-(void)keyClicked:(UIButton *)sender
{
    if (sender.tag==100) {
        
        
        controller = [[ShopViewController alloc] initWithStyle:UITableViewStylePlain items:reporttype tag:100];
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
        
        popover.tint = FPPopoverDefaultTint;
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            popover.contentSize = CGSizeMake(300, 500);
        }
        popover.arrowDirection = FPPopoverArrowDirectionUp;
        
        //sender is the UIButton view
        [popover presentPopoverFromView:sender];
        
    }
    else if (sender.tag > 110) {
        
        int category = sender.tag-110;
        
        //先获取点击的按钮的当前过滤条件，以此得到父ID
        KeyObject* key = [KeyFilter objectAtIndex:category-1];
        
        //若父ID为0则表示无上级目录，直接取这个过滤条件的所有项
        NSArray* arr = [[NSArray alloc]init];
        if (key.parentCode==0) {
            arr = [[DataManager sharedManager]getKeyObjects:category];
        }
        else{
            //有上次则根据上次获取该父亲下的所有子目录
            arr = [[DataManager sharedManager]getChildrenKeyObjects:key.parentCode];
        }
        
        
        /*
         popup = [[PopupView alloc] initWithFrame:sender.frame withItems:items withHighlight:0 width:sender.left+35 tag:sender.tag];
         popup.delegate = self;
         [self.view addSubview:popup];
         */
        //the controller we want to present as a popover
        controller = [[ShopViewController alloc] initWithStyle:UITableViewStylePlain items:arr tag:sender.tag];
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
        
        //popover.arrowDirection = FPPopoverArrowDirectionAny;
        popover.tint = FPPopoverDefaultTint;
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            popover.contentSize = CGSizeMake(300, 500);
        }
        popover.arrowDirection = FPPopoverArrowDirectionUp;
        
        //sender is the UIButton view
        [popover presentPopoverFromView:sender];
    }
    else if (sender.tag == 102) {
        NSArray *shop = [[DataManager sharedManager]getShopList];
        NSMutableArray *items = [NSMutableArray array];
        
        ShopObject* allshop = [[ShopObject alloc]init];
        allshop.shopName = @"全部店铺";
        [items addObject:allshop];
        for (int i = 0;i<shop.count;i++) {
            ShopObject *shopobj = [shop objectAtIndex:i];
            [items addObject:shopobj];
        }
        /*
         popup = [[PopupView alloc] initWithFrame:sender.frame withItems:items withHighlight:0 width:sender.left+35 tag:sender.tag];
         popup.delegate = self;
         [self.view addSubview:popup];
         */
        //the controller we want to present as a popover
        controller = [[ShopViewController alloc] initWithStyle:UITableViewStylePlain items:items tag:102];
        
        FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller];
        
        //popover.arrowDirection = FPPopoverArrowDirectionAny;
        popover.tint = FPPopoverDefaultTint;
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            popover.contentSize = CGSizeMake(300, 500);
        }
        popover.arrowDirection = FPPopoverArrowDirectionUp;
        
        //sender is the UIButton view
        [popover presentPopoverFromView:sender];
    }
}

-(void)refreshnum:(NSNotification *)sender
{
    
    NSDictionary* dic =  sender.object;
    
    KeyObject* key = [dic objectForKey:@"key"];
    
    [KeyFilter replaceObjectAtIndex:[[dic objectForKey:@"category"]intValue]-111 withObject:key];
    
    [self updateKeyButton:[[dic objectForKey:@"category"]intValue]-110];
    
    
    
#ifdef DHH_iOS
    [self refreshiphone:0 coatkeys:keys];
#else
    //[self refresh:0 keyname:key];
    [self newrefresh:selectedShopid ReportId:selecedReport];
    
    
#endif
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}


//选择某类报表后更新报表数据
-(void)refreshReport:(NSNotification *)sender
{
    NSDictionary *dic = sender.object;
    
    UIButton* reportbtn = (UIButton*)[tint viewWithTag:100];
    
    [reportbtn setTitle:[dic objectForKey:@"name"] forState:UIControlStateNormal];
    
    selecedReport = [[dic objectForKey:@"seq"]intValue]-1;
        
    if (selecedReport==10||selecedReport==11) {
        
        for ( int i = 0; i < keyCategories_.count; i++ ) {
            UIButton* btn = (UIButton*)[tint viewWithTag:111+i ];
            [btn setHidden:NO];
            //对过滤条件重新初始化一遍
            KeyObject* firstkey = [[[DataManager sharedManager]getKeyObjects:(i+1)]objectAtIndex:0];
            [KeyFilter replaceObjectAtIndex:i withObject:firstkey];
            [self updateKeyButton:i+1];
        }

    }
    else{
        for ( int i = 0; i < keyCategories_.count; i++ ) {
            UIButton* btn = (UIButton*)[tint viewWithTag:111+i ];
            [btn setHidden:YES];
        }
        [self newrefresh:selectedShopid  ReportId:selecedReport];

    }
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}
-(void)detail
{
    [self newrefresh:selectedShopid  ReportId:selecedReport];
}
-(void)graphic
{
    [view removeFromSuperview];
    [colorarr removeAllObjects];
    view = [[UIView alloc]initWithFrame:CGRectMake(0, tint.height, self.view.width, self.view.height-tint.height)];
    [self.view addSubview:view];
    
    UILabel *count = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    count.center = CGPointMake(view.width/4, 450);
    count.text = @"数量比图表";
    count.backgroundColor = [UIColor clearColor];
    [view addSubview:count];
    
    chart = [[XYPieChart alloc]initWithFrame:CGRectMake(0, 0, 400, 400)];
    [view addSubview:chart];
    chart.center = CGPointMake(view.width/4, view.height/2-100);
    chart.tag=10;
    chart.delegate = self;
    chart.dataSource = self;
    [chart reloadData];
    
    for (int i = 0; i<countarr.count; i++) {
        [colorarr addObject:[self pieChart:chart colorForSliceAtIndex:i]];
    }
    
    UILabel *price = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    price.center = CGPointMake(view.width*3/4, 450);
    price.text = @"金额比图表";
    price.backgroundColor = [UIColor clearColor];
    [view addSubview:price];
    
    chart = [[XYPieChart alloc]initWithFrame:CGRectMake(0, 0, 400, 400)];
    [view addSubview:chart];
    chart.center = CGPointMake(view.width*3/4, view.height/2-100);
    chart.tag=11;
    chart.delegate = self;
    chart.dataSource = self;
    [chart reloadData];
    
    for (int i = 0; i<countarr.count; i++) {
        UIView *color = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        color.backgroundColor = [colorarr objectAtIndex:i];
        color.center = CGPointMake(30 + 120*(i%8), 500 + (i/8)*40);
        [view addSubview:color];
        
        UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 30)];
        title.backgroundColor = [UIColor clearColor];
        title.text = [titlearr objectAtIndex:i];
        title.center = CGPointMake(30+100*(i%8), 500 + (i/8)*40);
        title.left = color.right+10;
        [view addSubview:title];
         
    }
    
}
-(void)refreshshop:(NSNotification *)sender
{
    NSDictionary *dic = sender.object;
    //NSString *str = [dic objectForKey:@"str"];
    int parentCategory = [[DataManager sharedManager] getParentCategoryCode:2];
    int filterCode = -1;
    if (parentCategory>=0) {
        NSArray *pArray = [[DataManager sharedManager] getKeyObjects:parentCategory];
        for (int i = 0; i < pArray.count; i++) {
            KeyObject *obj = [pArray objectAtIndex:i];
            if ([obj.keyName isEqualToString:coatname]) {
                filterCode = obj.keyID;
            }
        }
    }
    //NSArray *keys = [[DataManager sharedManager] getChildrenKeyObjects:filterCode];
    [totalshop setTitle:[dic objectForKey:@"title"] forState:UIControlStateNormal];
    //int num1 = [str intValue];
    
    selectedShopid = [dic objectForKey:@"shopid"];
#ifdef DHH_iOS
    [self refreshiphone:num1 coatkeys:keys];
#else
    [self newrefresh:selectedShopid  ReportId:selecedReport];
    
#endif
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissPopover" object:nil];
}
#pragma mark XYPieChart的代理
- (UIColor *)pieChart:(XYPieChart *)pieChart colorForSliceAtIndex:(NSUInteger)index {
    if (pieChart.tag == 10) {
        UIColor *color = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
        [colorarr addObject:color];
        return color;
    }
    else
    {
        return [colorarr objectAtIndex:index];
    }
}

- (NSUInteger)numberOfSlicesInPieChart:(XYPieChart *)pieChart{
    if (pieChart.tag == 10) {
        return countarr.count;
    }
    else
    {
        return pricearr.count;
    }
}

- (CGFloat)pieChart:(XYPieChart *)pieChart valueForSliceAtIndex:(NSUInteger)index{
    if (pieChart.tag == 10) {
       // static float gsValue[5] = {0.1,0.3,0.4,0.15,0.5};
        return [countarr[index] floatValue];
    }
    else
    {
      //  static float gsValue[5] = {0.1,0.3,0.4,0.15,0.05};
        return [pricearr[index] floatValue];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

@end
